package com.ungao.demo.config;

import com.ungao.framework.ApplicationContext;
import com.ungao.framework.define.BeanDefinition;
import com.ungao.framework.aware.InitializeAware;
import com.ungao.framework.session.SqlSession;
import com.ungao.framework.session.SqlSessionFactory;
import com.ungao.framework.session.build.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Set;

/**
 * ORM管理配置信息
 *
 * @author vic-ungao
 */
public class OrmConfig implements InitializeAware {

    /**
     * 应用上下文
     */
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void initialize() {

        //加载Mapper属性
        InputStream inputStream = this.getClass().getResourceAsStream("/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //注入ORM管理对象
        Set<Class> classList = sqlSessionFactory.getConfiguration().getMapperClasses();
        for (Class clazz : classList) {
            BeanDefinition beanDefinition = new BeanDefinition();
            String beanName = applicationContext.getBeanName(clazz);
            beanDefinition.put(beanName, sqlSession.getMapper(clazz));
            applicationContext.registerDefinition(beanName, beanDefinition);
        }
    }
}
